package ru.lenwp.operation.admin;

import ru.lenwp.util.ConsoleUtil;
import ru.lenwp.util.IOUtils;
import ru.lenwp.context.Context;
import ru.lenwp.model.Admin;
import ru.lenwp.model.Client;
import ru.lenwp.model.OperationInfo;
import ru.lenwp.model.User;
import ru.lenwp.operation.Operation;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

import static ru.lenwp.StringConstants.*;
import static ru.lenwp.StringConstants.ADMIN_LABEL;
import static ru.lenwp.StringConstants.EMAIL_CAPTION;

/**
 * Created by Lenar on 04.08.2014.
 */
public class LoadUsersOperation implements Operation {

    private final Context context;

    public LoadUsersOperation(Context context) {
        this.context = context;
    }

    public void readInfoUserDisk() {
        File flt = new File(ConsoleUtil.askString("Введите имя файла"));
        FileInputStream fr = null;
        try {
            fr = new FileInputStream(flt);
            Scanner sc = new Scanner(fr);
            while (sc.hasNext()) {
                String line = sc.nextLine();
                String[] segments = line.split(segmentDelimiter);
                User user = determinateUser(segments[0]);
                for (String segment : segments) {
                    String[] seg = segment.split(nameValueDelimiter, 2);
                    if (LOGIN.equals(seg[0])) {
                        user.setLogin(seg[1]);
                    } else if (FIRST_NAME_CAPTION.equals(seg[0])) {
                        user.setFirstName(seg[1]);
                    } else if (LAST_NAME_CAPTION.equals(seg[0])) {
                        user.setLastName(seg[1]);
                    } else if (SUR_NAME.equals(seg[0])) {
                        user.setSurName(seg[1]);
                    } else if (BIRTH_DATE.equals(seg[0])) {
                        user.setDate(new SimpleDateFormat().parse(seg[1]));
                    } else if (EMAIL_CAPTION.equals(seg[0])) {
                        user.setEmail(seg[1]);
                    }
                }
                context.getUserDao().insert(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(fr);
        }
    }

    private User determinateUser(String segment) {
        if (segment.endsWith(ADMIN_LABEL)) {
            return new Admin();
        }
        return new Client();
    }

    @Override
    public OperationInfo execute() {
        readInfoUserDisk();
        return null;
    }

    @Override
    public String getOperationName() {
        return "Загрузка данных из Файла";
    }
}
